<template>
  <div class="ai-assistant" :class="{ 'chat-open': isChatOpen }" v-show="isVisible">
    <!-- 悬浮图标 -->
    <div class="assistant-icon" @click="toggleChat">
      <div class="icon-wrapper">
        <div class="pulse-ring"></div>
        <div class="icon-container">
          <img src="@/assets/assistant.webp" alt="AI Assistant" class="ai-icon" />
        </div>
        <button class="close-icon" @click.stop="hideAssistant">×</button>
      </div>
    </div>

    <!-- 聊天窗口 -->
    <div class="chat-window" v-show="isChatOpen">
      <div class="chat-header">
        <h3>智能语音助手</h3>
        <button class="close-btn" @click="toggleChat">×</button>
      </div>
      <div class="chat-messages" ref="messageContainer">
        <div v-for="(message, index) in messages" :key="index" class="message" :class="message.type">
          <div class="message-content">
            <div v-if="message.type === 'assistant'" class="assistant-avatar">
              <img src="@/assets/assistant.webp" alt="AI Assistant" class="assistant-icon" />
            </div>
            <div class="message-text" :class="{ 'thinking': message.isThinking }">
              <template v-if="message.isThinking">
                <div class="thinking-animation">
                  <div class="dot"></div>
                  <div class="dot"></div>
                  <div class="dot"></div>
                </div>
              </template>
              <template v-else>
                {{ message.text }}
              </template>
            </div>
          </div>
        </div>
      </div>
      <div class="quick-actions" :class="{ 'quick-actions-hidden': !showQuickActions }">
        <div class="quick-actions-header">
          <h4>常见问题</h4>
          <button class="quick-actions-close" @click="toggleQuickActions">×</button>
        </div>
        <div class="quick-actions-content">
          <button v-for="action in quickActions" :key="action" class="quick-action-btn"
            @click="handleQuickAction(action)">
            {{ action }}
          </button>
        </div>
      </div>
      <div class="chat-input">
        <textarea
          v-model="userInput"
          @keyup.enter.exact="sendMessage"
          @keydown.enter.exact.prevent
          placeholder="输入您的问题..."
          class="chat-textarea"
          rows="4"
        ></textarea>
        <button class="send-btn" @click="sendMessage" :disabled="!userInput.trim()">
          <img :src="SendIcon" alt="发送" class="send-icon" />
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, onBeforeUnmount } from 'vue'
  import { useRouter } from 'vue-router'
  import messageSentAudio from '@/assets/video/message-sent.mp3'
  import messageReceivedAudio from '@/assets/video/message-receive.mp3'
  import SendIcon from '@/assets/svg/send.svg'
  import { getQuestionList } from '@/api/assistant.js'

  const router = useRouter()

  const isChatOpen = ref(false)
  const isVisible = ref(true)
  const userInput = ref('')
  const messages = ref([
    { type: 'assistant', text: '你好！我是智能语音助手，有什么可以帮你的吗？' }
  ])

  // 创建音频对象
  const sentAudio = new Audio(messageSentAudio)
  const receivedAudio = new Audio(messageReceivedAudio)

  const quickActions = [
    '如何使用文本转语音功能？',
    '如何制作个性化语音课件？',
    '如何管理和使用我的声音库？',
    '如何导出和分享我的语音作品？'
  ]
  
  const quickAnswers = {
    '如何使用文本转语音功能？': '使用文本转语音功能非常简单：\n1. 在输入框中输入您想要转换的文本\n2. 选择合适的语速和输出格式\n3. 点击"生成语音"按钮即可得到对应的音频\n4. 您可以预览、下载或直接使用生成的语音',
    '如何制作个性化语音课件？': '制作个性化语音课件的步骤：\n1. 上传或创建课件内容\n2. 选择需要配音的文本部分\n3. 为每段文本选择合适的语音风格\n4. 调整语速、语调等参数\n5. 预览并保存课件',
    '如何管理和使用我的声音库？': '声音库管理和使用指南：\n1. 在"我的声音库"中查看所有保存的语音\n2. 为语音添加标签和描述便于管理\n3. 可以编辑、删除或分享已保存的语音\n4. 支持按类别、日期等方式筛选语音\n5. 可以将常用语音添加到收藏夹',
    '如何导出和分享我的语音作品？': '导出和分享语音作品：\n1. 在作品页面选择要分享的语音\n2. 点击"导出"按钮选择导出格式\n3. 可以导出为MP3、WAV等格式\n4. 通过链接或二维码分享给他人\n5. 支持设置分享权限和有效期'
  }
  
  const showQuickActions = ref(true)
  
  const toggleQuickActions = () => {
    showQuickActions.value = !showQuickActions.value
  }

  const toggleChat = () => {
    isChatOpen.value = !isChatOpen.value
  }
  
    const messageContainer = ref(null)

  const scrollToBottom = () => {
    if (messageContainer.value) {
      setTimeout(() => {
        messageContainer.value.scrollTo({
          top: messageContainer.value.scrollHeight,
          behavior: 'smooth'
        });
      }, 100);
    }
  }

  const sendMessage = async () => {
      if (!userInput.value.trim()) return
      const userMessage = userInput.value.trim()
      messages.value.push({ type: 'user', text: userMessage })
      // 播放发送消息音效
      sentAudio.play()
      // 清空输入框
      userInput.value = ''
      
      // 检查是否是预设问题
      if (quickAnswers[userMessage]) {
        // 显示思考状态
        isThinking.value = true
        messages.value.push({
          type: 'assistant',
          text: '思考中...',
          isThinking: true
        })
        // 滚动到最新消息
        scrollToBottom()
        
        // 使用较短的延时来模拟思考
        setTimeout(() => {
          // 移除思考中的消息
          messages.value.pop()
          messages.value.push({
            type: 'assistant',
            text: quickAnswers[userMessage]
          })
          // 播放接收消息音效
          receivedAudio.play()
          // 滚动到最新消息
          scrollToBottom()
          isThinking.value = false
        }, 1000)
        return
      }

      // 显示思考状态
      isThinking.value = true
      messages.value.push({
        type: 'assistant',
        text: '思考中...',
        isThinking: true
      })
      // 滚动到最新消息
      scrollToBottom()
      try {
        // 调用后端接口获取AI回复
        const res = await getQuestionList({ prompt: userMessage })
        // 移除思考中的消息
        messages.value.pop()
        // 添加AI回复到消息列表
        messages.value.push({
          type: 'assistant',
          text: res.data || '抱歉，我暂时无法回答这个问题。'
        })
        // 播放接收消息音效
        receivedAudio.play()
        // 滚动到最新消息
        scrollToBottom()
      } catch (error) {
        // 移除思考中的消息
        messages.value.pop()
        // 处理错误情况
        messages.value.push({
          type: 'assistant',
          text: '抱歉，服务出现了一些问题，请稍后再试。'
        })
        // 滚动到最新消息
        scrollToBottom()
      } finally {
        isThinking.value = false
      }
    }
  const isThinking = ref(false)
  const handleQuickAction = (action) => {
    userInput.value = action
    sendMessage()
  }

  const hideAssistant = (e) => {
    e.preventDefault()
    isVisible.value = false
  }

  // 监听路由变化
  const handleRouteChange = () => {
    isVisible.value = true
    if (isChatOpen.value) {
      isChatOpen.value = false
    }
  }

  onMounted(() => {
    router.beforeEach((to, from, next) => {
      handleRouteChange()
      next()
    })
  })

  onBeforeUnmount(() => {
    // 清理路由监听器
    router.beforeEach(() => {})
  })
</script>

<style lang="scss" scoped>
  .ai-assistant {
    position: fixed;
    right: -30px;
    bottom: 650px;
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.4s ease;
    z-index: 1000;
  
    &:hover {
      right: 10px;
    }
  }

  .ai-assistant.chat-open {
    right: 30px;
  }

  .assistant-icon {
    width: 64px;
    height: 64px;
    background: linear-gradient(135deg, #579ff1, #2563EB);
    border-radius: 50%;
    cursor: pointer;
    box-shadow: 0 6px 20px rgba(74, 144, 226, 0.4);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: visible;
  }

  .assistant-icon:hover {
    transform: scale(1.05);
    box-shadow: 0 8px 24px rgba(74, 144, 226, 0.5);
  }

  .icon-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .icon-container {
    width: 42px;
    height: 42px;
    position: relative;
    z-index: 2;
  }

  .ai-icon {
    width: 100%;
    height: 100%;
    color: white;
    filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.15));
  }

  .pulse-ring {
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(74, 144, 226, 0.3) 0%, rgba(37, 99, 235, 0) 70%);
    opacity: 0;
    animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
      opacity: 0.4;
    }

    50% {
      transform: scale(1.2);
      opacity: 0;
    }

    100% {
      transform: scale(1);
      opacity: 0;
    }
  }

  .chat-window {
    position: fixed;
    z-index: 1001;
    top: 20px;
    right: 20px;
    width: 400px;
    height: calc(100vh - 40px);
    background: white;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    transform: translateX(100%);
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }

  .chat-open .chat-window {
    transform: translateX(0);
  }
  .chat-header {
    padding: 10px 24px;
    background: linear-gradient(135deg, #4A90E2, #357ABD);
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .chat-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    letter-spacing: 1px;
    text-shadow: 0 3px 4px rgba(0, 0, 0, 0.75);
    padding: 4px 0;
    line-height: 1.4;
  }

  .close-btn {
    background: none;
    border: none;
    color: rgba(255, 255, 255, 0.9);
    font-size: 28px;
    cursor: pointer;
    padding: 4px;
    line-height: 1;
    border-radius: 50%;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
  }

  .close-btn:hover {
    background: rgba(255, 255, 255, 0.1);
    color: #ffffff;
    transform: scale(1.05);
  }
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    padding-bottom: 10px;
    display: flex;
    flex-direction: column;
    gap: 16px;
    scroll-behavior: smooth;

    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
      width: 8px;
      margin-right: 2px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 4px;
      border: 1px solid #f1f1f1;

      &:hover {
        background: #a1a1a1;
      }
    }
  }

  .message {
    max-width: 80%;
    margin-bottom: 8px;
  }

  .message.user {
    align-self: flex-end;
  }

  .message.assistant {
    align-self: flex-start;
  }

  .message-content {
    display: flex;
    align-items: flex-start;
    gap: 8px;
  }

  .assistant-avatar {
    min-width: 36px;
    min-height: 36px;
    width: 36px;
    height: 36px;
    background: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    flex-shrink: 0;
    .assistant-icon {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }



  .message-text {
    padding: 14px 18px;
    border-radius: 16px;
    font-size: 15px;
    line-height: 1.6;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  }

  .assistant .message-text {
    background: linear-gradient(to bottom right, #F8F9FA, #E9ECEF);
    color: #2C3E50;
    border-radius: 3px 12px 12px 12px;
    margin-left: 4px;
  }

  .user .message-text {
    background: #4A90E2;
    color: white;
    border-radius: 12px 12px 0 12px;
  }

  .assistant .message-text {
    background: #F0F2F5;
    color: #333;
    border-radius: 12px 12px 12px 0;
  }

  .quick-actions {
    padding: 16px;
    background: #F8F9FA;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    margin: 0 20px 16px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    overflow: hidden;
  }

  .quick-actions-hidden {
    max-height: 0;
    padding: 0 12px;
    margin: 0 16px;
    opacity: 0;
  }

  .quick-actions-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    padding-bottom: 8px;
    border-bottom: 1px solid #E4E6E8;
  }

  .quick-actions-header h4 {
    font-size: 14px;
    font-weight: 600;
    color: #2C3E50;
    margin: 0;
  }

  .quick-actions-close {
    background: none;
    border: none;
    color: #9CA3AF;
    font-size: 18px;
    cursor: pointer;
    padding: 4px;
    line-height: 1;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
  }

  .quick-actions-close:hover {
    background: #F3F4F6;
    color: #4B5563;
  }

  .quick-actions-content {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .quick-action-btn {
    background: #F0F2F5;
    border: none;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 13px;
    color: #4A90E2;
    cursor: pointer;
    transition: all 0.2s ease;
    font-weight: 500;
  }

  .quick-action-btn:hover {
    background: #E4E6E8;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(74, 144, 226, 0.1);
  }

  .chat-input {
    padding: 12px 16px;
    display: flex;
    border-top: 1px solid #E4E6E8;
    align-items: flex-end;
    background: #fff;
    position: relative;
  }

  .chat-textarea {
    flex: 1;
    padding: 10px 16px;
    border: 2px solid #E4E6E8;
    border-radius: 16px;
    font-size: 14px;
    line-height: 1.5;
    outline: none;
    resize: none;
    transition: all 0.3s ease;
    min-height: 40px;
    max-height: 120px;
    overflow-y: auto;
  }

  .chat-textarea:focus {
    border-color: #4A90E2;
    box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
  }

  .send-btn {
    position: absolute;
    right: 24px;
    bottom: 20px;
    background: transparent;
    color: white;
    border: none;
    padding: 8px;
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 36px;
    min-width: 36px;
    box-shadow: 0 2px 6px rgba(72, 89, 109, 0.7);
  }

  .send-btn:hover:not(:disabled) {
    transform: scale(1.1);
  }

  .send-btn:disabled {
    cursor: not-allowed;
    opacity: 0.5;
  }

  .send-icon {
    width: 20px;
    height: 20px;
    fill: #4A90E2;
    transition: fill 0.2s ease;
  }

  .send-btn:hover:not(:disabled) .send-icon {
    fill: #357ABD;
  }

  .send-btn:disabled .send-icon {
    fill: #E4E6E8;
  }

  .close-icon {
    position: absolute;
    top: -8px;
    right: -5px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: linear-gradient(135deg, #ff4d4f, #ff7875);
    color: white;
    border: 1px solid white;
    font-size: 18px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    z-index: 3;
    box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
    transform: scale(0.9);
  }

  .assistant-icon:hover .close-icon {
    opacity: 1;
    transform: scale(1);
  }

  .close-icon:hover {
    background: linear-gradient(135deg, #ff7875, #ff9c9d);
    box-shadow: 0 4px 12px rgba(255, 77, 79, 0.4);
    transform: scale(1.1);
  }

  .thinking-animation {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    padding: 8px;

    .dot {
      width: 6px;
      height: 6px;
      background: #4A90E2;
      border-radius: 50%;
      animation: bounce 1.4s infinite ease-in-out both;

      &:nth-child(1) { animation-delay: -0.32s; }
      &:nth-child(2) { animation-delay: -0.16s; }
    }
  }

  @keyframes bounce {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1); }
  }

  .message-text.thinking {
    background: #F0F2F5;
    color: #666;
    font-style: italic;
  }
</style>